<?php
date_default_timezone_set('Asia/Shanghai');
define('DS', DIRECTORY_SEPARATOR);
define('ROOT_PATH', realpath(dirname(dirname(__FILE__))) . DS);

class Server
{
    private $serv;
    static private $options = "hdrmp:s:l:c:";
    static private $longopts = array("help", "daemon","reload", "monitor", "pid:", "log:", "config:","worker:","tasktype:","checktime:" );

    public function __construct() {
        $this->serv = new swoole_server("0.0.0.0", 9503);
        $this->config = parse_ini_file("../conf/config.ini", true);
    }

    public function run(){
        $this->serv->set($this->config['set']);
        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));

        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));

        $this->serv->on('Close', array($this, 'onClose'));
        $this->serv->on('WorkerStart', array($this, 'onWorkerStart'));
        $this->serv->start();
    }

    public function onStart( $serv ) {
    }


    public function onConnect( $serv, $fd, $from_id ) {
        echo "Client {$fd} connect\n";
    }

    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
        $data = trim($data);
        if($data == 'tt_reload'){
            $serv->reload();
        }

        //$this->command = new controllers\Command();
//{“code":10002301,"msg":"Database connect fail”,”data”:{}}
//        $result = $serv->taskwait("show tables");
//        if ($result !== false) {
//            $returns = $this->command->dos(json_decode($data, true));
//            $serv->send($fd, "Server: ".$data."\nreturns:".$returns);
//        } else {
//            $serv->send($fd, "Error. Task timeout\n");
//        }
    }

    public function onWorkerStart( $serv , $worker_id) {
        include_once('./namespace.php');
        if( $worker_id == 0 )
        {
            //Mysql run check
            $MySQL = new \library\MySQL();
            $MySQL->timeCheck();

            //crontab run start
            $opt = getopt(self::$options, self::$longopts);
            \extension\Main::run($opt);
        }
    }

    public function onTask( $serv, $task_id, $from_id, $data ){  //处理异步任务
        //返回任务执行的结果
         $serv->finish("$data -> OK");
    }

    function onFinish($serv, $data){
        echo "AsyncTask Finish:Connect.PID=" . posix_getpid() . PHP_EOL;
    }

    public function onClose( $serv, $fd, $from_id ) { //如果客户端关闭
        echo "Client {$fd} close connection\n";
    }

}

$server = new Server();
$server->run();
?>
